package com.yedou.util;

import cn.hutool.core.util.StrUtil;
import com.yedou.exception.ShareLockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisShareLockUtil {

    @Autowired
    private RedisUtil redisUtil;

    private Long TIME_OUT = 5000L;

    public boolean lock(String lockKey, String requestId, Long time) {
        if(StrUtil.isBlank(lockKey) || StrUtil.isBlank(requestId) || time <= 0){
            throw new ShareLockException("分布式锁-加锁参数异常");
        }
        long currentTime = System.currentTimeMillis();
        long outTime = currentTime + TIME_OUT;
        Boolean result = false;
        while (currentTime < outTime){
            // 它会在键（key）不存在时设置值（value） 如果设置成功，会同时设置这个 key 的过期时间
            result = redisUtil.setNx(lockKey, requestId, time, TimeUnit.MILLISECONDS);
            if(result){
                return result;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            currentTime = System.currentTimeMillis();
        }
        return result;

    }

    public boolean unLock(String key, String requestId) {
        if (StrUtil.isBlank(key) || StrUtil.isBlank(requestId)) {
            throw new ShareLockException("分布式锁-解锁-参数异常");
        }
        try {
            String value = redisUtil.get(key);
            if (requestId.equals(value)) {
                redisUtil.del(key);
                return true;
            }
        } catch (Exception e) {
            //补日志
        }
        return false;
    }

    public boolean tryLock(String lockKey, String requestId, Long time) {
        if (StrUtil.isBlank(lockKey) || StrUtil.isBlank(requestId) || time <= 0) {
            throw new ShareLockException("分布式锁-尝试加锁参数异常");
        }
        return redisUtil.setNx(lockKey, requestId, time, TimeUnit.MILLISECONDS);
    }


}
